<!-- 擅长领域管理 -->
<template>
	<!-- 面包屑区 -->
	<el-breadcrumb separator="/">
		<el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
		<el-breadcrumb-item :to="{ path: '/counselorInfo' }">咨询师信息管理</el-breadcrumb-item>
		<el-breadcrumb-item>擅长领域管理</el-breadcrumb-item>
	</el-breadcrumb>
	<!-- 查询 -->
	<el-form :inline="true" :model="queryInfo" class="demo-form-inline">
		<el-form-item label="擅长领域">
			<el-input v-model="queryInfo.greatName" placeholder="请输入擅长领域" clearable />
		</el-form-item>
		<el-form-item>
			<el-button type="primary" @click="queryDataList">搜索</el-button>
			<el-button type="primary" @click="add"> 新增擅长领域</el-button>
			<el-button type="danger" @click="batchRemove"> 批量删除</el-button>
		</el-form-item>
	</el-form>
	<!-- 对话框 -->
	<el-dialog :title="title" v-model="dialogFormVisible" width="950" @close="cancle">
		<el-form :model="GreatDate" label-width="100">
			<el-form-item label="擅长领域">
				<el-input v-model="GreatDate.greatName" autocomplete="off" placeholder="请输入擅长领域"></el-input>
			</el-form-item>
		</el-form>
		<template #footer>
			<div class="dialog-footer">
				<el-button @click="cancle">取 消</el-button>
				<el-button type="primary" @click="confirm">确 定</el-button>
			</div>
		</template>
	</el-dialog>
	<!-- 展示表格-->
	<el-table :data="dataList" row-key="id" style="width: 100%" @selection-change="handleSelectionChange">
		<el-table-column fixed="left" :data-="dataList" type="selection" width="55" />
		<el-table-column fixed="left" property="id" label="ID" width="60" />
		<el-table-column property="greatName" label="擅长领域" />
		<el-table-column fixed="right" label="操作" min-width="120">
			<template #default="scope">
				<el-button type="primary" size="small" @click="edit(scope.row)">编辑</el-button>
				<el-button type="danger" size="small" @click="remove(scope.row.id)">删除</el-button>
			</template>
		</el-table-column>
	</el-table>
	<!-- 书页组件 -->
	<el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[5,10,15,20]"
		:size="size" layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
		@current-change="handleCurrentChange" />

	<router-view></router-view>
</template>

<script lang="ts" setup>
	import { getCurrentInstance, onMounted, reactive, ref } from 'vue'
	import { ElMessage, ElMessageBox } from 'element-plus'
	import { Plus } from '@element-plus/icons-vue'
	import type { UploadProps, UploadUserFile } from 'element-plus'

	const { appContext } = getCurrentInstance()!
	const axios = appContext.config.globalProperties.axios

	const pageSize = ref(5);
	const currentPage = ref(1);

	const size = ref('default');


	const queryInfo = reactive({
		greatName: '',
		pageNum: 1,
		pageSize: 5
	})

	const total = ref(0);
	const dataList = ref<any[]>([])
	//存储复选的数据
	const multipleSelection = ref<number[]>([])
	const title = ref('')
	// 控制对话框是否显示
	const dialogFormVisible = ref(false)


	// // 查询数据
	const queryDataList = () => {
		axios.get(`/great/page`, {
			params: queryInfo,
		}).then((res) => {
			if (!res || !Array.isArray(res.list)) {
				dataList.value = []
				total.value = 0
				ElMessage.error("数据加载失败")
				return
			}
			dataList.value = res.list.map(item => ({
				id: item.id,
				greatName: item.greatName,
				del: item.del ?? 0
			}))
			total.value = res.total || 0
		})
			.catch(error => {
				ElMessage.error("查询失败")
			})
	}
	//组件加载完毕，查询数据
	onMounted(() => {
		queryDataList()
	})

	const handleSelectionChange = (val : any[]) => {
		multipleSelection.value = val.map(item => item.id)

	}
	//每页显示条目数改变
	const handleSizeChange = (val : number) => {
		queryInfo.pageSize = val;
		queryDataList();
	}
	//页码改变
	const handleCurrentChange = (val : number) => {
		queryInfo.pageNum = val;
		queryDataList();
	}

	// 新增和修改数据
	const GreatDate = ref({
		greatName: '',
		id: '',
		del: 0
	})


	const cancle = () => {
		GreatDate.value = {
			greatName: '',
			id: "",
			del: 0
		}
		dialogFormVisible.value = false
	}

	const confirm = () => {
		if (GreatDate.value.id) {
			axios.put(`/great/${GreatDate.value.id}`, GreatDate.value)
				.then((resp) => {
					if (resp.includes('成功')) {
						ElMessage.success('修改成功')
						dialogFormVisible.value = false
						queryDataList()
					} else {
						ElMessage.error('修改失败' + resp)
					}
					queryDataList()
					dialogFormVisible.value = false
				})
		} else {
			axios.post('/great', GreatDate.value)
				.then(resp => {
					if (resp.includes('成功')) {
						ElMessage.success("新增成功")
						dialogFormVisible.value = false
						queryInfo.greatName = ''
						queryDataList()
					} else {
						ElMessage.error("新增失败: " + resp)
					}
				})
				.catch(() => {
					ElMessage.error("新增请求失败")
				})
		}
	}

	const add = () => {
		title.value = '新增擅长领域'
		dialogFormVisible.value = true
	}

	const edit = (row) => {
		title.value = '编辑擅长领域'
		dialogFormVisible.value = true
		GreatDate.value = row

	}


	const remove = (id : number) => {
		if (!id) {
			ElMessage.warning("无效的删除目标")
			return
		}

		ElMessageBox.confirm('此操作永久删除该文件，是否继续？', '提示',
			{
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning',
			}).then(() => {
				axios.delete(`/great/${id}`)
					.then(resp => {
						if (resp.includes('成功')) {
							ElMessage.success('删除成功')
							queryDataList()
						} else {
							ElMessage.error(resp.data || "删除失败")
						}
					})
			}).catch(() => {
				ElMessage({
					type: 'info',
					message: '取消删除',
				})
			})
	}

	const batchRemove = () => {
		if (multipleSelection.value.length === 0) {
			ElMessage.warning('请选择要删除的项');
			return;
		}
		ElMessageBox.confirm('此操作永久删除该文件，是否继续？', '提示',
			{
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning',
			},
		).then(() => {
			const idsParam = multipleSelection.value.join(',');
			axios.delete(`/great`, {
				params: {
					ids: idsParam
				},
				paramsSerializer: params => {
					// 正确序列化数组参数
					return Object.keys(params)
						.map(key => `${key}=${params[key]}`)
						.join('&');
				}
			})
				.then(resp => {
					// 直接检查响应数据是否包含成功信息
					if (resp && resp.includes('成功')) {
						ElMessage.success("批量删除成功");
						queryDataList();
						multipleSelection.value = [];
					} else {
						ElMessage.error(`批量删除失败：${resp || '未知错误'}`);
					}
				})
		}).catch(() => {
			ElMessage({
				type: 'info',
				message: '取消删除',
			})
		})
	}
</script>

<style>
	.avatar-uploader .el-upload {
		border: 1px dashed var(--el-border-color);
		border-radius: 6px;
		cursor: pointer;
		position: relative;
		overflow: hidden;
		transition: var(--el-transition-duration-fast);
	}

	.avatar-uploader .el-upload:hover {
		border-color: var(--el-color-primary);
	}

	.el-breadcrumb {
		margin-bottom: 15px;
		padding: 0 0 15px;
		border-bottom: 1px solid #ddd;
	}

	.el-pagination {
		margin-top: 15px;
	}

	.demo-form-inline .el-input {
		--el-input-width: 220px;
	}

	.demo-form-inline .el-select {
		--el-select-width: 220px;
	}
</style>